<template>
  <a-card :bordered="false">
    <a-row :gutter="8">
      <a-col :span="3">
        <a-input-search v-model:value="searchValue" @search="onSearch" style="margin-bottom: 8px" placeholder="" />
      </a-col>

    </a-row>

    <a-row :gutter="8">
      <a-col :span="3">
        <!-- 加上 show-line 属性后，展开收起图标自动变成 +- 样式 -->
        <a-tree
          class="readRecords-tree"
          :tree-data="treeData"
          show-icon
          show-line
          :expandedKeys="treeExpandedKeys"
          :selectedKeys="[current]"
          @expand="handleTreeExpand"
          @select="handleTreeSelect"
        >
          <!-- 自定义子节点图标 :edit-config="{trigger: 'dblclick', mode: 'row'}" -->
          <a-icon slot="myIcon" type="unordered-list" style="color:#0c8fcf;"/>
          <template #title="{ title }">
            <span v-if="title.indexOf(searchValue) > -1">
              {{ title.substr(0, title.indexOf(searchValue)) }}
              <span style="color: #f50">{{ searchValue }}</span>
              {{ title.substr(title.indexOf(searchValue) + searchValue.length) }}
            </span>
            <span v-else>{{ title }}</span>
          </template>

        </a-tree>
      </a-col>
      <a-col :span="21">
        <div class="readNote">
          <div style="padding-left: 200px;">
            <span style="padding-left:50px;">用户数： {{t_read_num}}户</span>  
            <span style="padding-left:50px;">已抄数： {{readed_num}}次</span> 
            <span style="padding-left:50px;">未抄数： {{ n_read_num}}次 </span>
          </div>
          <div>
            操作提示：正常操作请输入止度并回车保存水量。如果需要自定义水量,请先选择对应的水表状态,然后再输入止度和水量并回车保存。 
          </div>
        </div>
         <!-- row-number          row-selection -->
        <j-vxe-table
         
          :height="750"
          :loading="loading"
          :columns="columns"
          :dataSource="dataSource"

          :mouse-config="{selected: true}"    
          :keyboard-config="{isEnter: true,  isEdit: true}"
          :edit-config="{trigger: 'dblclick', mode: 'cell', activeMethod: activeCellMethod}"  
   
          @edit-disabled="editDisabledEvent"
          @keydown="handleKeydown"
          @valueChange="handleValueChange"> 
                          
        </j-vxe-table>
      </a-col>
    </a-row>


  </a-card>
</template>

<script>
  import { getAction, postAction } from '@api/manage'
  import moment from 'moment'
  import { pushIfNotExist, randomNumber, randomUUID } from '@/utils/util'
  import { JVXETypes } from '@/components/jeecg/JVxeTable'

  // 【多种布局模板】左侧为树，右侧为行编辑
  export default {
    name: 'readRecordsList',
    data() {
      return {
        // 是否正在加载
        loading: false,
        onedit: false,
        searchValue:'',
        current: 1,
        currentKey: '',
        t_read_num: 0,
        r_read_num: 0,
        readed_num: 0,
        n_read_num: 0,
        
        // 选择的行
        selectedRows: [],
        // 数据源，控制表格的数据
        dataSource: [],
        // 列配置，控制表格显示的列
       columns: [
          {
            title: '户',
            key: 'customerId',
            type: JVXETypes.hidden,           
            fixed: 'left', 
          },
          {
            title: '本',
            key: 'bookId',
            type: JVXETypes.hidden,           
            fixed: 'left',          
          },
          {
            title: '本',
            key: 'isPassed',
            type: JVXETypes.hidden,           
            fixed: 'left',
            defaultValue: '0',
          },
          {
            title: '户号',
            key: 'cusCode',
            type: JVXETypes.normal,
            width: '80px',
            fixed: 'left',
            defaultValue: 'normal-new',
          },
          {
            title: '户名',
            key: 'cusName',
            type: JVXETypes.normal,
            width: '90px',
            fixed: 'left',
            defaultValue: 'normal-new',
          },
          {
            title: '地址',
            key: 'address',
            type: JVXETypes.normal,
            width: '120px',
            fixed: 'left',
            defaultValue: 'normal-new',
          },
          {
            title: '手机',
            key: 'mobile',
            type: JVXETypes.normal,
            width: '100px',
            fixed: 'left',
            defaultValue: 'normal-new',
          },
          // {
          //   title: '旧欠',
          //   key: 'normal',
          //   type: JVXETypes.normal,
          //   width: '80px',
          //   fixed: 'left',
          //   defaultValue: 'normal-new',
          // },
          // {
          //   title: '余额',
          //   key: 'normal',
          //   type: JVXETypes.normal,
          //   width: '80px',
          //   fixed: 'left',
          //   defaultValue: 'normal-new',
          // },
          {
            title: '起度',
            key: 'beginScale',
            type: JVXETypes.normal,
            width: '80px',
            defaultValue: 32,
          },
          {
            title: '止度',
            key: 'endScale',
            type: JVXETypes.inputNumber,            
            width: '80px',  
            validateRules: [{
              required: true,
              message: '${title}不能为空'
            }]             
          },
          {
            title: '水量',
            key: 'amount',
            type: JVXETypes.inputNumber,
            width: '80px',            
            validateRules: [{
              required: true,
              message: '${title}不能为空'
            }]  
          }, 
          {
            title: '抄表日期',
            key: 'readTime',
            width: '90px',
            type: JVXETypes.date,              
            defaultValue: ''         
          },    
          {
            title: '水表状态',
            key: 'waterUsedType',
            type: JVXETypes.select,
            width: '100px',
            options: [],          
            dictCode: 'water_used_type',
            placeholder: '请选择',
          },
          {
            title: '备注',
            key: 'remark',
            type: JVXETypes.input,
            width: '80px',
            defaultValue: '', 
          }
        ],
        // 树的数据，这里模拟分页固定数据，实际情况应该是后台查出来的数据
        treeData: [],
        // 树展开的列，默认 1-10
        treeExpandedKeys: [],
        // 查询url地址
        url: {
          getData: '/mr/mrBookMeters/queryBookMaterById',
          getTreeData: '/mr/book/queryBook',
          setManualData: '/mr/mrRecords/readManual',
          delManualData: '/mr/mrRecords/readDelManual',
        },
      }
    },
    created() {
      this.loadTreeData()     
    },
    methods: {

      //加载树数据
      loadTreeData(){
         // 封装查询条件
        let formData = {         
          code: '402881a97ebab91e017ebad45b5d0002'
        }
        // 调用查询数据接口
        this.loading = true
        getAction(this.url.getTreeData, formData).then(res => {
          if (res.success) {
            // 后台查询回来的 total，数据总数量
            // this.pagination.total = res.result.total
            // 将查询的数据赋值给 dataSource               
            this.treeData = res.result;          
            // this.treeExpandedKeys.push(res.result[0].key);
            // this.current=res.result[0].key;
            // 重置选择
            this.selectedRows = []
          } else {
            this.$error({title: '查询失败', content: res.message})
          }
        }).finally(() => {
          // 这里是无论成功或失败都会执行的方法，在这里关闭loading
          this.loading = false
        })
      },
      /* 查询加载表格数据 */
      randomPage(bookId, loading = false) {
        if (loading) {
          this.loading = true
        }
        this.readed_num=0;
        this.n_read_num=0;

        // 封装查询条件
        let formData = {         
          id: bookId,
          key: this.searchValue
        }
        // 调用查询数据接口
        this.loading = true
        getAction(this.url.getData, formData).then(res => {
          if (res.success) {
            // 后台查询回来的 total，数据总数量
            // this.pagination.total = res.result.total
            // 将查询的数据赋值给 dataSource               
            this.dataSource = res.result;
           
            //计算次数
            this.t_read_num=res.result.length;           
            for(var i=0;i<res.result.length;i++){
              let item= res.result[i];
              if( item.endScale > 0 ){
                this.readed_num++;
              }else{
                this.n_read_num++;
              }
            }

            this.dataSource.push(
              {customerId: '',  bookId: '', isPassed: '1',
                cusCode: '',cusName: '', addrees: '', mobile: '',
                beginScale: '', endScale: '', amount: '', }
            );
            //this.r_read_num=0;
           
          } else {
            this.$error({title: '查询失败', content: res.message})
          }
        }).finally(() => {
          // 这里是无论成功或失败都会执行的方法，在这里关闭loading
          this.loading = false
        }) 
      },

      onSearch(){
        //加载表格
        this.randomPage('', true)
      },

      /* 查询加载表格数据 */
      readSubmit(row, loading = false) {
        if (loading) {
          this.loading = true
        }

        // 调用查询数据接口
        this.loading = true
        postAction(this.url.setManualData, row).then(res => {
          if (res.success) {  
            this.$message.success("提交成功!")
          } else {
            this.$error({title: '查询失败', content: res.message})
          }
        }).finally(() => {
          // 这里是无论成功或失败都会执行的方法，在这里关闭loading
          this.loading = false
        }) 
      },
      /* 查询加载表格数据 */
      readDelSubmit(row, loading = false) {
        if (loading) {
          this.loading = true
        }

        // 调用删除数据接口
        this.loading = true
        postAction(this.url.delManualData, row).then(res => {
          if (res.success) {  
            this.$message.success("删除成功!")
          } else {
            this.$error({title: '删除失败', content: res.message})
          }
        }).finally(() => {
          // 这里是无论成功或失败都会执行的方法，在这里关闭loading
          this.loading = false
        }) 
      },

      // 树被选择触发的事件
      handleTreeSelect(selectedKeys,e) {         
        let key = selectedKeys[0]

        if(e.selectedNodes[0].data.props.dataRef.children){
           this.treeExpandedKeys = selectedKeys           
        }
        if(selectedKeys.length == 1){          
          //加载表格
          this.randomPage(key, true)
        }
      },

      // 树被选择触发的事件
      handleTreeExpand(expandedKeys) {
        this.treeExpandedKeys = expandedKeys
      },
      handleValueChange(event) {
        const { type, row, column, value, target } = event  

        if( event.col.key=='endScale' ){
          let bs= event.row.beginScale;
          let es= event.row.endScale;
          let wut= event.row.waterUsedType;
          let am= event.row.amount;
          if( es == undefined ||  es == '' ){
            es=0;
          }

          let a= es-bs;
          if(a>0){            
            let am=[{rowKey: event.row.id, values: {'amount': a }}]
            target.setValues(am)
            if(this.currentKey==13 && wut == 1){
              //提交
              this.readSubmit(event.row,true);

              this.readed_num++;            
              this.n_read_num--;
            }
          }else{
            if(es == 0 ){
              let am=[{rowKey: event.row.id, values: {'amount': '' }}]
              target.setValues(am);
              if(this.currentKey==13){
                //提交删除
                this.readDelSubmit(event.row,true);
                this.readed_num--;
                this.n_read_num++;
              }
            }
          }           
        }else if( event.col.key=='amount' ){         
          let wut= event.row != null && event.row.waterUsedType !=null ? event.row.waterUsedType:-1;
          let am= event.row != null && event.row.amount !=null ? event.row.amount: -1 ;
       
          //不是正常状态
          if(wut != 1){
            if(am >= 0){
              //有水量就可以提交
              if(this.currentKey==13){
                //提交
                this.readSubmit(event.row,true);
                this.readed_num++;
                this.n_read_num--;
              }
            }
          }               
        }  
      },     
      handleEnter(event){    
        console.log('handleEnter.event: ', event.row)
      },
  
      editDisabledEvent (event) {    
        if (event.row.isPassed == '1') {
          this.$message.info("已上锁!")
        }
      },
      activeCellMethod (event) {
        if (event.row.isPassed == '1') {
          return false
        }
        return true
      },

      handleKeydown(event){
        this.currentKey=event.$event.keyCode;
        if(event.$event.keyCode == 13){
          //this.handleValueChange(event);
          // console.log('handleKeydown.keyCode: ', event.$event.target.className)      
        }
      },
    },
  }
</script>

<style lang="less">
  /** 隐藏文件小图标 */
  .template-5-tree.ant-tree {
    li span.ant-tree-switcher.ant-tree-switcher-noop {
      display: none;
    }
  }
  .readNote{
    border: 1px solid #eeeff1;
    line-height:32px;
    padding: 0 50px;
    color: blue;
  }
</style>